<script setup>
import { ref } from 'vue'
import HeaderComponent from '@/components/HeaderComponent.vue'
import FooterComponent from '@/components/FooterComponent.vue'
import { MdEditor } from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import { message } from 'ant-design-vue'

let postTitle = ref('【无标题】')
const text = ref('# Hello Editor')
// 图片上传
const onUploadImgHandler = async (files, callback) => {
	alert('上传图片：' + files[0].name)
	const res = await Promise.all(
		files.map(file => {
			return new Promise((rev, rej) => {
				const form = new FormData()
				form.append('file', file)

				fetch('/api/img/upload', {
					method: 'POST',
					body: form,
					headers: {
						'Content-Type': 'multipart/form-data',
					},
				})
					.then(res => rev(res))
					.catch(error => rej(error))
			})
		})
	)
	// 回调返回图片地址
	callback(res.map(item => item.data.url))
}

// 保存草稿
const saveHandler = () => {
	message.error('功能待开发中...！')
}

// 发送文章
const sendHandler = () => {
	message.info('发布成功！内容为：' + text.value)
}
</script>

<template>
	<HeaderComponent />
	<!-- 文章标题 -->
	<a-flex gap="small" class="post-title">
		<a-input v-model:value="postTitle" size="large" placeholder="请输入文章标题" show-count :maxlength="100" />
		<a-button danger size="large" @click="saveHandler">保存草稿</a-button>
		<a-button type="primary" danger size="large" @click="sendHandler">发布文章</a-button>
	</a-flex>
	<!-- Markdown文章编写组件 -->
	<MdEditor :toolbarsExclude="['pageFullscreen', 'fullscreen', 'htmlPreview', 'catalog', 'github']" editorId="editorMD" id="editorMD" v-model="text" @onUploadImg="onUploadImgHandler" />
	<!-- 底部版权说明 -->
	<FooterComponent />
</template>
<style scoped>
.post-title {
	width: 90%;
	margin: 15px auto;
}
.post-title :deep(.ant-input) {
	background-color: #fff;
}
#editorMD {
	height: calc(100vh - 168px);
}
</style>
